package socket;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 多人聊天
 */
public class ClientDemo {
    private Socket socket;
    public ClientDemo(){
        try {
            System.out.println("正在链接服务器");
            socket = new Socket("176.28.2.17", 8088);//localhost  176.28.2.20
            System.out.println("与服务器链接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try{
            OutputStream out =  socket.getOutputStream();
            OutputStreamWriter ost = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(ost);
            PrintWriter pw = new PrintWriter(bw,true);

            Scanner scan = new Scanner(System.in);
            System.out.println("请输入你的用户名");
            pw.println(scan.nextLine());
            Runnable c = new ClientHread(socket);
            Thread th = new Thread(c);
            th.start();
            String st ;
            while (true){
                st = scan.nextLine();
                if ("exit".equals(st)){
                    break;
                }
                pw.println(st);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        ClientDemo client = new ClientDemo();
        client.start();
    }
    class ClientHread implements Runnable{
        private Socket socket;

        public ClientHread(Socket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            try {
                System.out.println("线程2开启");
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String st ;
                //System.out.println("这里是接收");
                while (true){
                    st = br.readLine();
                    if (st==null){
                        System.out.println("聊天已结束");
                        break;
                    }
                    System.out.println(st);
                }
            }catch (IOException o){
                System.out.println("程序发生错误");
            }
        }
    }
}
